<template>
  <continer
    :showPage="showPage"
    :shadow="true"
    :pageshadow="true"
    :isNoTabs="true"
  >
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFun"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="handleSearchFun"
        >查询</el-button
      >
      <el-button
        size="mini"
        @click="addBtnFun"
        v-functions="['spare_mgt_warehouse_insert']"
        >新建</el-button
      >
    </template>
    <template slot="content">
      <instiutionTable
        ref="tableRef"
        @currentChange="currentChangeFun"
        @sizeChange="sizeChange"
        :pages="spareTablePages"
        :instiutionTableData="spareTableData"
        :instiutionTableHeader="spareTableHeader"
      >
      <template #belongArea="{ scope }">
        {{areaMap[scope.row.province]}}<template v-if="scope.row.city">/{{areaMap[scope.row.city]}}</template><template v-if="scope.row.area">/{{areaMap[scope.row.area]}}</template>
      </template>
      </instiutionTable>
    </template>
    <template slot="page">
      <createWareHouse
        ref="wareHouse"
        :areaOptions="areaOptions"
        :titleArr="titleArr"
        :edit="edit"
        @pageBack="returnPage"
        @cancelFun="returnPage"
        @handleSaveFun="handleSaveFun"
      />
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import createWareHouse from '@/afterSales/views/spare/houseInfo/createWareHouse.vue'
import { ElForm } from 'element-ui/types/form'
import { commonAction, deepClone } from '@/utils/common'
import { Store } from 'vuex/types'
import { mutations } from '@/afterSales/views/spare/store/spareData'
import { checkPermission } from '@/utils/directive'
@Component({
  name: 'HouseInfo',
  components: {
    QuickSearch,
    continer,
    instiutionTable,
    createWareHouse
  }
})
export default class Category extends Vue {
  @Ref() private readonly wareHouse!: createWareHouse
  private $store: Store<any> | undefined
  private $confirm: any
  private $message: any

  private $getCache: any

  private titleArr: any[] = []

  private showPage: boolean = false

  private edit = false // 是否为编辑

  private areaOptions: any = [] // 地区数据

  private spareTableData = [] // 表格数据

  private spareTableHeader: any[] = [ // 表头
    { label: '仓库名称', prop: 'name' },
    { label: '仓库管理员', prop: 'adminName' },
    { label: '所属地区', prop: 'belongArea', custom: true },
    { label: '详细地址', prop: 'address' }
  ]

  private spareTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 100
  }

  private quickSearchForm: any = {} // 快捷检索数据

  private get areaMap () {
    const labels = {}
    const handleFn = (list) => {
      list.map(item => {
        labels[item.id] = item.fullname
        if (item.children) {
          handleFn(item.children)
        }
      })
    }
    if (this.areaOptions && this.areaOptions.length) {
      handleFn(this.areaOptions)
    }
    return labels
  }

  private currentChangeFun (page: number) { // 翻页
    this.spareTablePages.current = page
    this.getTableList()
  }

  private sizeChange (size: number) {
    this.spareTablePages.pageSize = size
    this.getTableList()
  }

  private handleSearchFun () { // 搜素
    this.spareTablePages.current = 1
    this.getTableList()
  }

  private getAgentName (agentId) {
    const agent = (this.$store as Store<any>).state.common.publicCache.userListObj[agentId]
    if (agent) {
      return agent.name
    }
    return ''
  }

  private getTableList () { // 获取表格数据
    const { admin, wareHouseName, address, areaList } = this.quickSearchForm.form
    const sendData = {
      limit: this.spareTablePages.pageSize,
      page: this.spareTablePages.current,
      admin: admin ? [admin] : [],
      wareHouseName,
      address,
      province: areaList && areaList.length ? areaList[0] : '',
      city: areaList && areaList.length >= 2 ? areaList[1] : '',
      area: areaList && areaList.length === 3 ? areaList[2] : ''
    }
    commonAction({
      url: '/server-work/action/wareHouse/list',
      method: 'post',
      data: sendData
    }).then(res => {
      if (res.success) {
        const { list, count } = res.data
        list.map(item => { // 拼接地区字段
          item.adminName = this.getAgentName(item.admin)
        })
        this.spareTableData = list
        this.spareTablePages.total = count
      }
    })
  }

  private saveSparePartsConfirm () { // 保存
    const formRef = this.wareHouse.$refs.accessForm as ElForm
    const sendData = this.wareHouse.accessForm
    formRef.validate(valide => {
      if (valide) {
        commonAction({
          url: '/call/action/cdr/tag',
          method: 'post',
          data: sendData
        }).then(res => {
          if (res.success) {
            this.$message.success('创建成功')
          }
        })
      }
    })
  }

  private addBtnFun () { // 新建
    this.edit = false
    this.showPage = true
    this.titleArr = ['新建仓库']
    this.$nextTick(() => {
      this.wareHouse.accessForm = {
        name: '',
        admin: [],
        areaList: [],
        address: '',
        memo: ''
      }
    })
  }

  private editFun (row: any) {
    this.edit = true
    this.showPage = true
    this.titleArr = ['编辑仓库']
    this.$nextTick(() => {
      if (row.area) {
        row.areaList = [row.province, row.city, row.area]
      } else if (!row.area && row.city) {
        row.areaList = [row.province, row.city]
      } else {
        row.areaList = [row.province]
      }
      row.admin = row.admin[0]
      this.wareHouse.accessForm = deepClone(row)
    })
  }

  private handleSaveFun () { // 新建保存
    this.showPage = false
    this.getTableList()
  }

  private returnPage () { // 新增返回列表
    this.showPage = false
  }

  private handleDel (row: any) { // 删除
    this.$confirm('确定要删除该仓库吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      commonAction({
        url: '/server-work/action/wareHouse/delete',
        method: 'post',
        data: { id: row.id }
      }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getTableList()
        }
      })
    })
  }

  private areaSelectList (): void {
    this.$getCache('/base/action/general/cache/query', ['region'], false).then(res => {
      if (Object.keys((this.$store as Store<any>).state.common.publicCache.region).length) {
        this.areaOptions = (this.$store as Store<any>).state.common.publicCache.region?.result
        const userList = (this.$store as Store<any>).state.common.publicCache.userList || []
        this.quickSearchForm = { // 快捷检索数据
          form: {
            wareHouseName: '',
            admin: [],
            areaList: [],
            address: ''
          },
          advSearchOptions: [
            { label: '仓库名称', inputType: 'input', placeholder: '请输入', name: 'wareHouseName', clearable: true },
            { label: '仓库管理员', inputType: 'select', clearable: true, selectData: userList, name: 'admin', defaultProp: { label: 'agentName', value: '_id' } },
            { label: '所属地区', inputType: 'cascader', clearable: true, filterable: true, options: this.areaOptions, name: 'areaList', props: { label: 'fullname', value: 'id', children: 'children' } },
            { label: '详细地址', inputType: 'input', placeholder: '请输入', name: 'address', clearable: true }
          ]
        }

        this.$nextTick(() => {
          this.getTableList()
        })
      }
    })
  }

  private deactivated () {
    mutations.setRequestData('house', false) // 重新请求仓库数据
  }

  private mounted () {
    let handlers: any[] = []
    if (checkPermission(null, { value: ['spare_mgt_warehouse_edit'] })) {
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) })
    }
    if (checkPermission(null, { value: ['spare_mgt_warehouse_delete'] })) {
      handlers = [...handlers,
        ...[{ className: 'danger', name: '删除', handleFn: (scope: any) => this.handleDel(scope.row) }]
      ]
    };
    this.spareTableHeader.push({ label: '操作', width: 100, handlers })
    this.areaSelectList()
  }
}
</script>
